import type { FC } from 'react'
import React from 'react'
import { withNativeProps } from '../../../src/utils/native-props'
import { type ComponentProps } from '../../global/common-style'

const classPrefix = `gd-file-picker`

export type FilePickerProps = {
  id?: string
  /**
   * 是否可以多选
   * @type {boolean}
   */
  multiple?: boolean
  /**
   * 用于调用设备的摄像头或麦克风
   * @type {boolean | 'user' | 'environment' | undefined;}
   */
  capture?: boolean | 'user' | 'environment' | undefined
  /**
   * 可接受的文件类型
   * @type {string | undefined}
   */
  accept?: 'image/*' | 'audio/*' | 'video/*' | undefined
  /**
   * max
   */
  max?: number | string | undefined
  /**
   * min
   */
  min?: number | string | undefined
  /**
   *
   * @returns onchange
   */
  onChange: (fileList: File[]) => void
} & ComponentProps &
  React.PropsWithChildren<object>

export const FilePicker: FC<FilePickerProps> = (props) => {
  const { multiple = false, capture, accept, max, min, id = 'file' } = props

  function onClick() {
    const fileDom = document.getElementById(id)
    fileDom?.click()
  }

  const onFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (!event.target.files) {
      return
    }
    const filesList = Object.values(event.target.files)
    props?.onChange(filesList)
  }

  return withNativeProps(
    props,
    <div className={`${classPrefix}`}>
      <input
        id={id}
        type="file"
        accept={accept}
        multiple={multiple}
        style={{ display: 'none' }}
        capture={capture}
        max={max}
        min={min}
        onChange={(e) => {
          onFileChange(e)
        }}
      />
      <div
        onClick={() => {
          onClick()
        }}
      >
        {props.children}
      </div>
    </div>
  )
}
